package com.lambkit.generator;

import com.lambkit.core.Lambkit;
import com.lambkit.db.IDb;
import com.lambkit.db.dialect.IDialect;
import com.lambkit.generator.template.TemplateEngine;
import com.lambkit.util.Printer;

import javax.sql.DataSource;
import java.util.Map;

public abstract class BaseGenerator implements IGenerator {

	protected GeneratorContext context;

	public void context(IDb db, Map<String,Object> options, GeneratorConfig config) {
		DataSource dataSource = db.getDataSource();
		IDialect dialect = db.getDialect();
		options.put("dialect", dialect);
		context(dataSource, options, config);
	}
	@Override
	public void context(DataSource dataSource, Map<String,Object> options, GeneratorConfig config) {
		if(config == null) {
			//模板地址，根目录是项目文件夹
			config = new GeneratorConfig();
			//生成java代码的存放地址
			String outRootDir = options.get("outRootDir")==null ? Lambkit.context().resourceService().getWebRootPath() : options.get("outRootDir").toString();
			config.setOutRootDir(outRootDir);
			//生成java代码的包地址
			String basePackage = options.get("basePackage")==null ? "com.lambkit.msch" : options.get("basePackage").toString();
			config.setBasepackage(basePackage);
			//生成前端文件文件夹
			String webpages = options.get("webpages")==null ? "app" : options.get("webpages").toString();
			config.setWebpages(webpages);
			//表格配置方式
			String mgrdb = options.get("mgrdb")==null ? "normal" : options.get("mgrdb").toString();
			config.setMgrdb(mgrdb);
			//选择一种模板语言
			String engine = options.get("engine")==null ? GeneratorConfig.TYPE_VELOCITY : options.get("engine").toString();
			config.setEngine(engine);
			//选择一种处理引擎
			String type = options.get("type")==null ? GeneratorType.DB.getValue() : options.get("type").toString();
			config.setType(type);
		}
		Printer.print(this, "generator", getClass() + " create GeneratorContext");
		this.context = new GeneratorContext(config);
		if(dataSource!=null) {
			this.context.setDataSource(dataSource);
		}
		if(options!=null && options.get("dialect") !=null) {
			this.context.setDialect((IDialect) options.get("dialect"));
		}
		if(options!=null && options.get("templateEngine") !=null) {
			Object templateEngine = options.get("templateEngine");
			if(templateEngine instanceof TemplateEngine) {
				this.context.setTemplate((TemplateEngine) templateEngine);
			}
		}
		String configName = options.containsKey("configName") ? options.get("configName").toString() : null;
		this.context.setConfigName(configName);
	}

	public GeneratorContext getContext() {
		return context;
	}

	public void setContext(GeneratorContext context) {
		this.context = context;
	}
	
}
